package com.mg.plugin.agrometeorology.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateCalculator {
    private static DateCalculator instance;
    private Calendar calendar;

    private DateCalculator() {
        calendar = Calendar.getInstance();
    }

    public static Date calcLastTime(Date parse, int i) throws ParseException {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(calcTime(parse, i));
        calendar1.add(Calendar.DATE, -5);
        return calendar1.getTime();
    }

    public int getMonth(String strDate, String strDateFormat) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        Date date = sdf.parse(strDate);
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    public static DateCalculator getInstance() {
        if (instance == null) {
            instance = new DateCalculator();
        }

        return instance;
    }

    public int getDay(String strDate, String strDateFormat) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        Date date = sdf.parse(strDate);
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static Date calcTime(Date parse, int count) throws ParseException {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(parse);
        int month = (int) (3 + Math.floor(count / 6));
        int day = count % 6 * 5 + 5;
        if (day == 30 && (month != 3 && month != 5)) {
            day = 31;
        }
        calendar1.set(Calendar.MONTH, month);
        calendar1.set(Calendar.DAY_OF_MONTH, day);
        return calendar1.getTime();
    }

    public static Date calcTendaysBeforeTime(Date parse, int count) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(parse);
        int month = (int) (3 + Math.floor(count / 6));
        int day = count % 6 * 5 + 5;
        if (day == 30 && (month != 3 && month != 5)) {
            day = 31;
        }
        calendar1.set(Calendar.MONTH, month);
        calendar1.set(Calendar.DAY_OF_MONTH, day - 10);
        return calendar1.getTime();
    }
}
